<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>外呼客户号码库</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
      </el-form-item>
      <el-form-item label="" v-for="(filter, index) in searchParams.filters" :key="index">
        <el-input size="small" v-model="filter.fieldValue" v-bind:fieldName="filter.fieldName" v-if="filter.showAble"
                  v-bind:fieldValue="filter.fieldValue" v-bind:compare="filter.compare" :disabled="filter.readonly"
                  @keyup.enter.native="search"
                  :placeholder="filter.placeholder" :readonly="filter.readonly" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" type="success" icon="el-icon-upload" @click="upload()">上传</el-button>
        <el-button size="small" type="warning" icon="el-icon-download" @click="downloadTemplate()">下载模板</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table size="small" :data="list" highlight-current-row v-loading="loading" border
              element-loading-text="拼命加载中"
              style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column align="center" prop="phone" label="手机号" width="150">
      </el-table-column>
      <el-table-column align="center" prop="infomation" label="信息">
      </el-table-column>
      <el-table-column align="center" prop="updateAt" label="更新时间" width="160">
      </el-table-column>
      <el-table-column align="center" label="操作" width="160">
        <template slot-scope="scope">
          <el-button size="mini" @click="showDetails(scope.$index, scope.row)">详情</el-button>
          <el-button size="mini" type="danger" @click="deleteItem(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageParams" @callFather="callFather"/>


    <el-dialog :title="'上传'" :visible.sync="editFormVisible" :close-on-click-modal="false" width="30%"
               style="text-align: center;"
               @click='closeDialog("edit")'>
      <el-upload
        class="upload-demo"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        drag
        :action="'base/zsInfo/imports/' + this.$route.query.id"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过500kb</div>
      </el-upload>
    </el-dialog>

    <el-dialog :title="'号码详情'" :visible.sync="detailParams.showAble" :close-on-click-modal="false" width="30%"
               @click='closeDialog("edit")'>

      <el-form label-width="120px" :model="detailParams.selectedItem" ref="editForm" readonly>
        <el-form-item :label="item" prop="seatNum" v-for="(item, index) in Object.keys(infomation)" :key="index">
          <el-input size="small" v-model="infomation[item]" readonly disabled placeholder="请输入坐席号码"/>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
  import {downloadTemplate, infoDelete, infoList, seatAdd, seatEdit} from "../../../api/baseMG";
  import Pagination from '../../../components/Pagination';

  export default {
    data() {
      return {
        selectedItem: {},
        list: [],
        editFormVisible: false,
        loading: false,
        editForm: {},
        rules: {},
        // 分页参数
        pageParams: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        searchParams: {
          orderBy: 'update_at desc',
          page: 1,
          perPage: 10,
          filters: [
            {
              showAble: true,
              readonly: false,
              placeholder: "请输入手机号",
              fieldName: "phone",
              compare: "like",
              fieldValue: ""
            },
            {
              showAble: false,
              readonly: false,
              fieldName: "surveyId",
              compare: "=",
              fieldValue: this.$route.query.id
            }
          ],
          isLock: ''
        },
        detailParams: {
          showAble: false,
          selectedItem: {
            infomation: {}
          }
        },
        infomation: {}
      }
    },
    created() {
      this.search();
    },
    // 注册组件
    components: {
      Pagination
    },
    methods: {
      showDetails(index, item) {
        this.detailParams.selectedItem = item;
        this.detailParams.showAble = true;
        this.infomation = JSON.parse(item.infomation);
      },
      uploadSuccess(response, file, fileList) {
        if (response.success) {
          this.editFormVisible = false;
          this.$message.success(response.msg);
        } else {
          this.$message.error(response.msg);
        }
      },
      uploadError(err, file, fileList) {
        console.log(err, file, fileList)

      },
      upload() {
        this.editFormVisible = true;
      },
      userSelectorResultHandler(items) {
        let item = items[0];
        this.selectedItem.uid = item.userId;
        this.selectedItem.workNum = item.workNum;
        this.selectedItem.state = 1;
        this.updateItem(this.selectedItem, () => {
          this.selectorParams.showAble = false;
        });
      },
      closeUserSelectorDialog() {
        this.selectorParams.showAble = false;
      },
      changeSeatStatus(row) {
        this.$confirm('确定要释放该坐席吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.updateItem({id: row.id, state: 0, uid: null});
        }).catch(err => {
          console.error(err);
          this.search(this.formInline);
        })
      },
      // 关闭编辑、增加弹出框
      closeDialog(dialog) {
        if (dialog === 'edit') {
          this.editFormVisible = false
        } else if (dialog === 'perm') {
          this.dataAccessshow = false
        } else if (dialog === 'unit') {
          this.unitAccessshow = false
        }
      },
      submitAddForm(params) {
        this.$refs[params].validate(valid => {
            if (valid) {
              if (!this.editForm.id) {
                seatAdd(this.editForm).then(resp => {
                  if (resp.success) {
                    this.$message({
                      type: 'success',
                      message: resp.msg
                    });
                    this.editFormVisible = false;
                    this.search();
                  } else {
                    this.$message({
                      type: 'error',
                      message: resp.msg
                    });
                  }
                })
              } else {
                this.updateItem(this.editForm);
              }
            }
          }
        );
      },
      downloadTemplate() {
        downloadTemplate(this.$route.query.id).then(resp => {
          let blob = new Blob([resp.data]);
          let url = window.URL.createObjectURL(blob);
          let a = document.createElement('a');
          a.href = url;
          a.download = '问卷号码导入模板.xlsx';
          a.click();
          window.URL.revokeObjectURL(url);
        }).catch(err => {
          console.log(err);
        })
      },
      // 分页插件事件
      callFather(param) {
        this.searchParams.page = param.currentPage;
        this.searchParams.perPage = param.pageSize;
        this.getList(this.searchParams);
      },
      handleEdit(index, row) {
        this.editTitle = "修改坐席";
        this.editForm = {
          id: row.id,
          seatNum: row.seatNum,
          password: row.password,
          uid: row.uid,
          workNum: row.workNum
        };
        this.editFormVisible = true
      },
      search() {
        this.initSearchParams();
        this.getList(this.searchParams);
      },
      initSearchParams() {
        console.log(this.$route)
        for (let i = 0; i < this.searchParams.filters.length; i++) {
          let item = this.searchParams.filters[i];
          if (item.fieldName === 'queueId' && this.$route.query.queueId) {
            item.fieldValue = this.$route.query.queueId;
          }
        }
      },
      getList(params) {
        infoList(params).then(resp => {
          if (resp.success) {
            this.list = resp.data.list;
            this.pageParams.currentPage = resp.data.pageNum;
            this.pageParams.pageSize = resp.data.pageSize;
            this.pageParams.total = resp.data.total;
          }
        })
      },
      updateItem(item, c) {
        seatEdit(item).then(res => {
          if (res.success) {
            this.$message({
              type: 'success',
              message: res.msg
            });
            this.search(this.formInline);
            if (c) {
              c();
            }
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        }).catch(err => {
          console.log(err)
          this.loading = false;
          this.$message.error('释放失败，请稍后再试！')
        })
      },
      deleteItem(index, row) {
        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          infoDelete(row.id).then(res => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: res.msg
              });
              this.search(this.formInline)
            } else {
              this.$message({
                type: 'info',
                message: res.msg
              })
            }
          }).catch(err => {
            this.loading = false;
            this.$message.error('删除失败，请稍后再试！')
          })
        }).catch(err => {
          console.error(err);
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .upload-demo {
    width: 100%;
    text-align: center;
  }
</style>
